<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=Ru9A27vdhk7cHEvvS97bz4CNLUpBjYKv"></script>
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
        src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
</head>

<body>
    <div id="allmap" style="overflow:hidden;zoom:1;position:relative;width: 1000px;height: 800px;">
        <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">
        </div>
    </div>
    <div id="result">
        <input type="button" value="获取绘制的覆盖物个数" onclick="alert(overlays.length)" />
        <input type="button" value="清除所有覆盖物" onclick="clearAll()" />
    </div>

    <script>
        // 百度地图API功能
        var map = new BMap.Map('map');
        var poi = new BMap.Point(116.307852, 40.057031);
        map.centerAndZoom(poi, 16);//设置中心点坐标和地图级别
        map.enableScrollWheelZoom(); //启用鼠标滚动对地图放大缩小

        //鼠标绘制完成回调方法   获取各个点的经纬度
        var overlays = [];
        var overlaycomplete = function (e) {
            overlays.push(e.overlay);
            var path = e.overlay.getPath();//Array<Point> 返回多边型的点数组
            for (var i = 0; i < path.length; i++) {
                console.log("lng:" + path[i].lng + "\n lat:" + path[i].lat);
            }
        };
        var styleOptions = {
            strokeColor: "red",    //边线颜色。
            fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
            strokeWeight: 3,       //边线的宽度，以像素为单位。
            strokeOpacity: 0.8,       //边线透明度，取值范围0 - 1。
            fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
            strokeStyle: 'solid' //边线的样式，solid或dashed。
        }
        //实例化鼠标绘制工具
        var drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingMode: BMAP_DRAWING_POLYGON,//绘制模式  多边形
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                offset: new BMap.Size(5, 5), //偏离值
                drawingModes: [
                    BMAP_DRAWING_POLYGON
                ]
            },
            polygonOptions: styleOptions //多边形的样式
        });

        //添加鼠标绘制工具监听事件，用于获取绘制结果
        drawingManager.addEventListener('overlaycomplete', overlaycomplete);
        function clearAll() {
            for (var i = 0; i < overlays.length; i++) {
                map.removeOverlay(overlays[i]);
            }
            overlays.length = 0
        }
    </script>
</body>

</html>